package com.JingYan.util;

import lombok.extern.slf4j.Slf4j;
import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;
import net.sourceforge.tess4j.util.LoadLibs;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;


import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.Charset;

/**
 * OCR 文字识别
 *
 * @author Dong_Jia_Qi on 2022/4/21
 */
@Slf4j
public class OcrUtil {
    public static void main(String[] args) throws TesseractException {
        File imgDir = new File("G:\\图片\\Saved Pictures\\毕业证明.png");
        imgOcr(imgDir);
    }

    private static String imgOcr( File imgDir) throws TesseractException {
        String ocrResult;
        ITesseract instance = new Tesseract();
        // log.info(OcrUtil.class.getClassLoader().getResource("application.yml").getPath());
        // File f = new File(OcrUtil.class.getResource("application.yml").getPath());
        // log.info(f.getPath());
        Resource resource =  new ClassPathResource("tessdata");
        File file = null;
        try {
            file = resource.getFile();
            String path = resource.getURL().getPath();
            log.info(path);
        } catch (IOException e) {
            log.error("获得本地路径失败",e);
        }
        String path = file.getPath();
        // log.info(path);
        //如果未将tessdata放在根目录下需要指定绝对路径
        instance.setDatapath(path);

        //如果需要识别英文之外的语种，需要指定识别语种，并且需要将对应的语言包放进项目中
        instance.setLanguage("chi_sim");
        try {
            ocrResult = instance.doOCR(imgDir);
            log.info(ocrResult);
        } catch (TesseractException e) {
            log.error(e.getMessage(),e);
            throw e;
        }
        return ocrResult;
    }
}
